package leetcode.code1864;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minSwaps1(String s) {
		char[] cs = s.toCharArray();
		int len = cs.length;
		// 假设以1开头，需要交换n11个1，需要交换n10个0
		int s1 = 1, n11 = 0, n10 = 0;
		// 假设以0开头，需要交换n01个1，需要交换n00个0
		int s0 = 0, n01 = 0, n00 = 0;
		for (int i = 0; i < len; i++) {
			int cur = cs[i] - '0';
			if (s1 == 1) {
				n11 += (cur & 1) == 1 ? 0 : 1;
			} else {
				n10 += (cur & 1) == 1 ? 1 : 0;
			}
			if (s0 == 1) {
				n01 += (cur & 1) == 1 ? 0 : 1;
			} else {
				n00 += (cur & 1) == 1 ? 1 : 0;
			}
			s1 ^= 1;// 相邻10互换
			s0 ^= 1;// 相邻10互换
		}
		int ans = n11 == n10 ? n11 : -1;
		return n01 == n00 ? ans == -1 ? n01 : Math.min(ans, n01) : ans;
	}

	// 简化代码
	public int minSwaps(String s) {
		char[] cs = s.toCharArray();
		int len = cs.length;
		// 假设以1开头，需要交换n11个1，需要交换n10个0
		int s1 = 1, n11 = 0, n10 = 0;
		// 假设以0开头，需要交换n01个1，需要交换n00个0
		int n01 = 0, n00 = 0;
		for (int i = 0; i < len; i++) {
			boolean one = cs[i] == '1';
			if (s1 == 1) {
				n11 += one ? 0 : 1;
				n00 += one ? 1 : 0;
			} else {
				n10 += one ? 1 : 0;
				n01 += one ? 0 : 1;
			}
			s1 ^= 1;// 相邻10互换
		}
		int ans = n11 == n10 ? n11 : -1;
		return n01 == n00 ? ans == -1 ? n01 : Math.min(ans, n01) : ans;
	}

	@Override
	public void debug4() {
		H.compare(1, this.minSwaps("111000"));
		H.compare(0, this.minSwaps("010"));
		H.compare(-1, this.minSwaps("1110"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
